﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Reflection;
using Volo.Abp;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;

namespace Joy.Erp.BasicArchives.EntityFrameworkCore
{
    public static class DbContextModelCreatingExtensions
    {
        public static void AssemblyConfigure(this ModelBuilder builder, Assembly assembly)
        {
            Check.NotNull(builder, nameof(builder));

            var types = assembly.GetTypes().Where(IsModelConfiguration);

            foreach (var type in types)
            {
                IModelConfiguration modelConfiguration = (IModelConfiguration)Activator.CreateInstance(type);
                modelConfiguration.Build(builder);
            }
        }

        public static void AssemblyEntity(this IAbpDbContextRegistrationOptionsBuilder options, Assembly assembly)
        {
            Check.NotNull(options, nameof(options));

            var types = assembly.GetTypes().Where(IsModelConfiguration);

            foreach (var type in types)
            {
                IModelConfiguration modelConfiguration = (IModelConfiguration)Activator.CreateInstance(type);
                modelConfiguration.Entity(options);
            }
        }

        public static bool IsModelConfiguration(Type type)
        {
            if (!type.IsPublic || type.IsAbstract || type.IsGenericType)
            {
                return false;
            }

            if (typeof(IModelConfiguration).IsAssignableFrom(type))
            {
                return true;
            }

            return false;
        }
    }
}
